using System;
using System.Collections.Generic;
using System.Text;

namespace PocketAbapa
{
	public class FieldServices
	{
		public FieldServices(Field mField)
		{
			this.field = mField;
		}

		private Field field;

		public int RedistributeBalls(int Position)
		{
			if (!IsValidPosition(Position))
			{
				return 0;
			}

			int ballCount = field[Position].Balls;
			int nextPosition = Position;
			field[Position].Balls = 0;
			
			for (int i = 0; i < ballCount; i++)
			{
				IncPosition(ref nextPosition);
				if (nextPosition == Position)
				{
					IncPosition(ref nextPosition);
				}
				field[nextPosition].Balls++;
			}

			int anyBallsCollected = CollectBalls(nextPosition);
			field.Players.Current.Score += anyBallsCollected;

			return anyBallsCollected;
		}

		public int CollectBalls(int Position)
		{
			int CollectedBalls = 0;
			int CollectedBallsSum = 0;

			int currentBalls = field[Position].Balls;
			int currentPosition = Position;

			while (
				(currentBalls == 2 || currentBalls == 3)
				&& Distance(Position, currentPosition) < 5)
			{
				CollectedBalls ++;
				CollectedBallsSum += currentBalls;

				IncPosition(ref currentPosition);
				currentBalls = field[currentPosition].Balls;
			}

			currentPosition = Position;

			if (CollectedBalls <= 5)
			{
				for (int i = 0; i < CollectedBalls; i++)
				{
					field[currentPosition].Balls = 0;
					IncPosition(ref currentPosition);
				}
				return CollectedBallsSum;
			}
			else
			{
				return 0;
			}
		}

		public int Distance(int Position1, int Position2)
		{
			if (Position2 >= Position1)
			{
				return Position2 - Position1;
			}
			else
			{
				return Position2 + 12 - Position1;
			}
		}

		public int IncrementPosition(int Position, int Step)
		{
			return (Position + Step) % NumberOfButtons;
		}

		public void IncPosition(ref int Position, int Step)
		{
			Position = IncrementPosition(Position, Step);
		}

		public void IncPosition(ref int Position)
		{
			IncPosition(ref Position, 1);
		}

		public bool IsValidPosition(int Position)
		{
			return Position >= 0 && Position < NumberOfButtons;
		}

		public int NumberOfButtons
		{
			get
			{
				return 2 * field.FieldSize;
			}
		}
	}
}
